package db

import (
	"fmt"

	"functime"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
)

var engine *xorm.Engine

func init() {
	var err error
	engine, err = xorm.NewEngine("mysql", "root:123456@/test?charset=utf8")
	err = engine.Sync(new(User))
	engine.SetTableMapper(core.SameMapper{})
	engine.SetColumnMapper(core.SnakeMapper{})
	if err != nil {
		fmt.Println("mysql error:", err)
	}
}

func Mysql_InitData() {
	for i := 0; i < PlayerNum; i++ {
		uid := 1000 + i + 1

		users := make([]User, 0)
		engine.Where("u_i_d = ?", uid).Find(&users)
		if len(users) >= 1 {
			continue
		}

		user := NewUser(uid)
		n, err := engine.Insert(user)
		if err != nil {
			fmt.Println("mysql init data:", n, err)
			break
		}
	}
}

func Mysql_RunStress() {
	fc := functime.NewFuncTime()
	defer fc.End("Mysql_RunStress")

	//	wg := sync.WaitGroup{}

	for n := 0; n < PlayerNum; n++ {
		//		wg.Add(1)
		func() {
			users := make([]User, 0)

			where := ""
			for i := 1; i <= FriendNum; i++ {
				uid := 1000 + i
				if i == 50 {
					where = where + fmt.Sprintf("u_i_d = %d", uid)
				} else {
					where = where + fmt.Sprintf("u_i_d = %d or ", uid)
				}
			}

			err := engine.Where(where).Find(&users)
			if err != nil {
				fmt.Println("mysql stress:", err)
			}
			//			wg.Done()
		}()
	}

	//	wg.Wait()

	//	spew.Dump(users)
}
